Exploiting the Top 10 API Vulnerabilities with vAPI

Author: Khasan Abdurakhmanov Author's Avatar

Affiliation: Innopolis University Author's Avatar

TABLE OF CONTENTS

Introduction

The OWASP API Security Top 10 highlights the most critical API security risks that developers and organizations should be aware of. This guide provides a walkthrough for exploiting these vulnerabilities using vAPI, a self-hosted PHP interface designed to replicate OWASP API Top 10 scenarios through exercises. vAPI, available on GitHub at https://github.com/roottusk/vapi, can be easily set up by following the instructions in the README.md file. The walkthrough covers how to configure Postman and other tools to test the various API vulnerabilities.

Tools and Setup

In order to gain a comprehensive understanding of the vulnerabilities you are dealing with and to exploit them effectively, it is imperative to have a collection of specific tools at your disposal. Here is a list of the essential tools you will need:

  1. Postman

    Postman has garnered popularity as a highly effective tool for testing APIs. It provides an intuitive user interface that allows you to easily send HTTP requests and closely examine the responses you receive. You have the option to use either the desktop application or the web version, depending on your preference.


  1. Docker

    Docker is a platform that has gained wide acceptance for containerization. It greatly simplifies the process of managing and deploying applications in containers, making it a vital tool for any developer.


  1. Burp Suite

    Burp Suite is a formidable tool in the realm of web application security testing. It offers a wide array of features, suitable for both manual and automated testing. It plays a vital role in intercepting and analyzing HTTP requests and responses, making it indispensable for security testing.


Postman and Burp Suite are both popular tools used for API testing, but they serve different purposes:

Combining Postman and Burp Suite in this guide can be beneficial for the following reasons:

  1. Postman can be used to create and execute API requests, while Burp Suite can intercept and analyze the traffic to identify potential security issues.

  2. Burp Suite can be used to test APIs for vulnerabilities like injection flaws, broken authentication, and security misconfigurations, which are covered in the OWASP API Security Top 10.

  3. Using both tools together provides a more comprehensive approach to API testing, leveraging the strengths of each tool.

Docker is chosen as the containerization tool in this guide for several reasons:

  1. Docker is the most popular and widely-used containerization platform, with a large and active community.

  2. Docker provides a consistent and reproducible environment for running applications, making it easier to set up and deploy the vAPI application.

  3. Docker simplifies the management of dependencies and ensures that the application runs consistently across different environments.

In addition to Docker, this guide will also use Docker Compose to define and manage the multi-container application. Docker Compose allows you to define the services, networks, and volumes required for the application in a single configuration file, making it easier to set up and manage the environment.


Setting Up vAPI

There are two ways to set up vAPI: using Docker Engine or manually. Both methods are detailed below.

Method 1: Using Docker Engine

  1. Clone the vAPI Repository
    First, clone the vAPI repository from GitHub to your local machine:

git clone https://github.com/roottusk/vapi.git cd vapi
  1. Build and Run the vAPI Container
    Use Docker Compose to build and run the vAPI container:
docker-compose up -d

  1. Access vAPI
    Open http://localhost:80 in your web browser to access the vAPI interface.


Method 2: Setting Up vAPI Manually

Prerequisites:


  1. Clone the vAPI Repository
    First, clone the vAPI repository from GitHub to your local machine:
git clone https://github.com/roottusk/vapi.git cd vapi

  1. Set Up the Database

Here are the steps to create a new user and database in MySQL:

sudo mysql -u root
CREATE DATABASE new_database;
CREATE USER 'new_user'@'localhost' IDENTIFIED BY 'new_password';
GRANT ALL PRIVILEGES ON new_database.* TO 'new_user'@'localhost';
FLUSH PRIVILEGES;
exit

That’s it! You have now created a new database called new_database and a new user called new_user with the password new_password. The user has been granted all privileges on the new database.

A few things to note:

Next we should import vapi.sql into our MySQL database:

mysql -u your_username -p your_database < vapi.sql

  1. Configure DB Credentials
    Configure the database credentials in the vapi/.env file with your database details.

  1. Starting MySQL Service
    Start the MySQL service (Linux):
sudo systemctl restart mysql.service

  1. Starting Laravel Server
    Go to the vAPI directory and run the Laravel development server:
composer update composer install

This will update the project dependencies to their latest compatible versions, which may resolve some issues.

php artisan serve --host=0.0.0.0

  1. Access vAPI:

Open http://localhost:80 in your web browser to access the vAPI interface.


Setting Up Postman

Import Collection:

Use Public Workspace:

Deployment

Helm can be used to deploy to a Kubernetes namespace. The chart is located in the vapi-chart folder. This chart requires a secret named vapi with the following values:

DB_PASSWORD: <database password to use> DB_USERNAME: <database username to use>

Here is a sample Helm Install Command:

helm upgrade --install vapi ./vapi-chart --values=./vapi-chart/values.yaml`

The MYSQL_ROOT_PASSWORD value on line 232 in the values.yaml file must match the one on line 184 for the deployment to work properly.


Exploiting Vulnerabilities

Let’s begin our exploitation journey by examining the first vulnerability in the OWASP API Security Top 10:

1. Broken Object-Level Authorization (BOLA)

Explanation

In this vulnerability, a user can access data belonging to another user by manipulating a parameter, such as an id. For example, if your user ID is 5 and you change the id parameter to 6, you might be able to see another user’s data. This type of vulnerability is known as Insecure Direct Object References (IDOR).

Steps to Exploit
To demonstrate this vulnerability, we will use API endpoints that allow us to create a user and access user data using an id parameter.

  1. Creating New User

Send a POST request to /api/1/users with the necessary parameters to create a new user.

Endpoint: /vapi/api1/user

HTTP Method: POST

Authorization: No authorization required (noauthAuth)

Headers:

{ "username": "alice", "name": "Alice", "course": "Computer Science", "password": "password123" }

You should receive a response with the newly created user’s data, including the id parameter.

{ "id": 5, "username": "alice", "name": "Alice", "course": "Computer Science", }

  1. Access Your User Data

Send a GET request to /api/1/users/{id}, replacing {id} with the id of the user you just created.

Endpoint: /vapi/api1/user/{api1_id}

HTTP Method: GET

Headers:


To calculate the Basic Authorization token, follow these steps:

  1. Combine your username and password with a colon (:) separator. For example, if your username is alice and password is password123, the concatenated string would be alice:password123.

  2. Encode the concatenated string using Base64 encoding. You can use online tools or programming languages to perform Base64 encoding.

For the example credentials:

The Basic Authorization token would be:

YWxpY2U6cGFzc3dvcmQxMjM=

You should be able to see your own user data in the response.

Expected Response:

{ "id": 5, "username": "alice", "name": "Alice", "course": "Computer Science", }

  1. Exploit IDOR by Accessing Another User’s Data

To exploit the IDOR vulnerability, change the id parameter to another value, such as 1, and send the request again.

Endpoint: /vapi/api1/user/1

HTTP Method: GET

Headers:

If you receive the data for another user, such as Michael in this example, it confirms that the application is vulnerable to IDOR.


  1. Update User

The last endpoint in /vapi/api1 is the PUT Update user which gives the user the facility to update the information. This is another instance of the Broken Object Level Authorization (BOLA) vulnerability in the vAPI project. This time, it’s in the PUT endpoint for updating a user’s information.

Let’s go through the steps to exploit this vulnerability:

  1. Retrieve the user data you want to update:
    • You likely used the GET /api/1/users/{id} endpoint to retrieve the details of the user with id=1.

  1. Modify the user data in the request body:
    • You updated the user data in the request body, potentially changing the name, email, or other fields.

  1. Send the PUT request with the modified user ID:
    • Instead of using your own user ID in the request, you changed the api1_id parameter to 1, which corresponds to the user you don’t have permission to update.

Despite the lack of authorization checks, the server accepted the request and updated the information for the user with id=1, even though you don’t have the necessary permissions to do so.

This is a clear example of a BOLA vulnerability, where the server fails to properly validate the user’s authorization to perform the requested action on a specific resource (in this case, the user with id=1).


2. Broken Authentication

The second vulnerability we’ll explore is Broken Authentication, which allows an attacker to bypass authentication mechanisms and impersonate legitimate users.This can happen due to weak passwords, default credentials, brute-force attacks, or unauthorized access to tokens or credentials.

In API2, there are two endpoints:

An attacker can exploit weak authentication mechanisms to gain unauthorized access to a user’s account. This can be done by:

Endpoints

  1. User Login Endpoint
    • HTTP Method: POST
    • Endpoint: /vapi/api2/user/login
    • Request Body:
{ "email":"savanna48@ortiz.com", "password":"zTyBwV/9" }

  1. Get Details Endpoint
    • HTTP Method: GET
    • Endpoint: /vapi/api2/user/details
    • Headers:
      • Authorization-Token: Fp0r1mty_gxK9DRZ5IUw3sX2enQ6rau68M6YGyoqR3XoBG13wtSbvmdaK5CB

In this scenario, there’s a file called creds.csv in the resource folder containing numerous IDs and passwords. We can use Burp Suite to automate the login attempts and find valid credentials.

To exploit the broken authentication vulnerability in API 2 using Burp Suite, we’ll capture the login request and send it to the Intruder. We’ll configure the attack to use credentials from the creds.csv file.

Step-by-Step Guide

  1. Open Burp Suite:
    • Launch Burp Suite and ensure your browser is configured to route traffic through Burp’s proxy.

  1. Capture the Login Request:
    • In your browser, navigate to the login endpoint of the vAPI application.
    • Enter a test email and password, then attempt to log in.
    • Burp Suite will capture the request.

  1. Send Request to Intruder:
    • In Burp Suite, go to the “Proxy” tab and find the captured login request in the “HTTP history” sub-tab.
    • Right-click on the login request and select “Send to Intruder”.

  1. Configure Intruder:
    • Go to the “Intruder” tab and select the “Positions” sub-tab.
    • Highlight the email and password fields in the request body and click “Add §” to mark them as positions to be attacked.

  1. Set Attack Type:
    • Set the attack type to “Pitchfork”. This allows Burp Suite to pair each email with a corresponding password from the payloads.

  1. Load Payloads:
    • Go to the “Payloads” sub-tab.
    • For Payload set 1 (email), click “Load” and select the creds.csv file. This will load the list of emails.
    • For Payload set 2 (password), click “Load” and select the creds.csv file again. This will load the list of passwords.

  1. Start the Attack:
    • Click “Start attack” to begin the brute-force attack.
    • Burp Suite will try each combination of email and password.

  1. Analyze Results:
    • Once the attack is complete, look for successful login attempts in the “Intruder results” window.
    • Successful logins will typically have a different response status or length compared to failed attempts.

By following these steps, you can exploit broken authentication vulnerabilities using Burp Suite. This allows you to identify weak or default credentials and gain unauthorized access to user accounts.


3. Excessive data exposure

We often share more data than necessary. This API response includes unnecessary information, which users may exploit.

To investigate, we use an APK from the resources folder in our emulator. Next, we exploit the API using a tool like Burp Suite. We set up a proxy, intercept the request, and send it to the repeater for testing.

The response reveals excessive data exposure, providing an easy flag. Despite the API returning extensive data upon login, not all is displayed. A tool like Burp Suite reveals this needless data exposure.


4. Lack of resources and rate-limiting

APIs often lack proper protection against excessive client-side requests, making them vulnerable to denial-of-service (DoS) attacks or allowing attackers to bypass authentication systems by flooding the server with requests. This vulnerability demonstrates how to exploit APIs that do not implement rate limiting.

In this scenario, we have three endpoints:

Exploiting Lack of Resources and Rate Limiting

At this stage, we have encountered an obstacle: the OTP (One-Time Password) is unknown to us. However, we can gather from the response body of the previous request that the OTP is likely composed of four digits. Moreover, there seems to be no rate limiting, which suggests that we have an opportunity to attempt a brute force approach to ascertain the OTP.

To implement this, we’ll first need to capture the request. This can be done by manually entering any random 4 digits. We’ll use Burp Suite for this, a popular tool in the field of web security. Once we have captured the request with our inputted 4-digit code, we will then forward it to the intruder tab of Burp Suite. This process will enable us to automate the brute force attack, by cycling through all possible 4-digit combinations until the correct OTP is found.

The first step in the process is to select the OTP (One-Time Passcode) value, which will be used as the payload, and set the attack type to sniper. This is critical because the OTP forms the basis of our payload and the sniper attack type is efficient for this operation.

After completing the first step, navigate to the payload tab in the interface. Here, you will need to configure the payload type and various payload options. Specifically, set the payload type to numbers. This is because the OTP value we are using is numeric.

In the payload options, adjust the settings as depicted in the screenshot provided above. It’s important to follow these settings carefully, as they determine how the payload will be generated and used in the attack. By following these steps, you can ensure that the process is carried out effectively.

**We can see the correct OTP **

Yes we got the key I think it’s time for our FLAG


5. Broken function-level authorization

Broken function-level authorization occurs when an API improperly enforces what functions users can access. This can lead to unauthorized users performing actions they shouldn’t be able to or accessing data they shouldn’t have.

In this example, we’ll demonstrate how a normal user can manipulate the request method to retrieve information or perform actions that should be restricted.

Steps to Exploit

Captured Request:

POST /vapi/api5/create_user HTTP/1.1 Host: 158.160.154.200 Accept-Encoding: gzip, deflate, br Accept: */* Content-Type: application/json Content-Length: 75 { "username":"testuser2", "password":"test123", "name":"Test User", "address":"ABC", "mobileno":"888888888" }

Okay, let’s calculate the Basic Authentication token for the provided user credentials:

{
    "username": "testuser2",
    "password": "test123",
    "name": "Test User",
    "address": "ABC",
    "mobileno": "888888888"
}

The steps to calculate the Basic Authentication token are:

  1. Concatenate the username and password with a colon (:) separator:

    testuser2:test123
    
  2. Encode the concatenated string using Base64 encoding:

    dGVzdHVzZXIyOnRlc3QxMjM=
    

The resulting Basic Authentication token is:

dGVzdHVzZXIyOnRlc3QxMjM=

Captured Request:

GET /vapi/api5/users HTTP/1.1 Host: 158.160.154.200 Accept-Encoding: gzip, deflate, br Accept: */* Content-Type: application/json Content-Length: 75 Authorization-Token:dGVzdHVzZXIyOnRlc3QxMjM=

Now we will intercept this request and try to see the details of all users as I think there should be our flag.

This demonstrates that the server-side code is not properly validating the user’s permissions and authorizing the requested action. The server is allowing the user to perform an action (retrieving the user list) that they should not have access to.


6. Mass assignment

Mass assignment vulnerability occurs when an API accepts user input without properly filtering or validating it, allowing attackers to add unexpected or unauthorized data to the request. This can lead to unauthorized access or modification of sensitive features.

Let’s explore how to exploit this vulnerability in the vAPI project.

Exploitation Steps

Good, you’ve successfully created a new user using the API 6 endpoint and obtained an authentication token in the response. This token can now be used to access the user details in the next endpoint.

Here we notice an intriguing parameter: credit.

Let’s incorporate this parameter into our first endpoint and see if we can increase our credit. 😈

This demonstrates how the Mass Assignment vulnerability can be exploited to gain unauthorized access to sensitive data or functionality within the API. By manipulating the request to include unexpected fields, an attacker can potentially bypass intended access controls and gain elevated privileges or access to restricted resources.


7. Security misconfiguration

Security misconfiguration can occur due to default or incomplete configurations, misconfigured HTTP headers, improper Cross-Origin Resource Sharing (CORS) settings, and verbose error messages containing sensitive data. These flaws can be exploited by attackers to gain unauthorized access or bypass security measures.

In this scenario, we will explore security misconfigurations by interacting with various endpoints and examining their configurations.

Endpoints

Next, we enter the authentication token and log in. In this weak encryption, the auth_token is regular base64 encoded.

Once we’ve successfully logged in, we proceed to the next endpoint, where we secure the key. This process is crucial in our task, as suggested by the lab description, where we are required to exploit a Cross-origin Request.

The term origin refers to a specific header that is included in the request. Its primary function is to establish a security context for the origin request. This is applicable in all scenarios except for the ones in which the original information might be sensitive or unnecessary, where it would not be prudent to use it.

To execute this, we introduce a header in this request. We choose to assign it the value https://bing.com. This value is not randomly selected but is chosen for specific reasons that will help us achieve our goal more effectively. It is this careful and strategic planning that will enable us to complete the task at hand successfully.


8. Injection

Injection vulnerabilities are prevalent and highly impactful, consistently appearing in the OWASP Top 10 list. These vulnerabilities occur when untrusted input is sent to an interpreter as part of a command or query. The interpreter executes this input without proper validation or sanitization, leading to unintended and potentially harmful execution of commands or queries.

In this scenario, we will explore injection vulnerabilities by interacting with endpoints and attempting to inject malicious inputs.

Endpoints

  1. User Login
  2. Get Secret

Attempt to log in using random credentials to understand the login mechanism.

Since we cannot log in using random credentials, we will attempt SQL injection to bypass authentication.

As the lab name indicates, I attempted SQL injection and received a MYSQL error.

After exploiting this error, I obtained the auth token.

The payload I used was ‘or’1’='1. Feel free to try others as well.

After successfully obtaining the authentication token, we were able to make use of it in our subsequent interactions with the system. We utilized this auth token as a means of verification when sending requests from the second endpoint. This was a critical step in our process, and it was indeed successful. The result was exactly what we were hoping for - we managed to retrieve the FLAG!!!

This demonstrates how Injection vulnerabilities, such as SQL injection, can be exploited to bypass authentication and authorization controls, leading to the disclosure of sensitive data or even the execution of arbitrary commands on the server.


9. Improper assets management

Improper assets management refers to the failure to properly inventory, manage, and retire API versions and endpoints. When older versions of APIs are not properly deprecated or secured, they can expose vulnerabilities that have been fixed in newer versions.

In this scenario, we will explore how an attacker can exploit improper asset management by accessing an outdated version of an API.

When we send a request, we receive a response that indicates rate-limiting is enabled. This brings up the question of what steps we can take to successfully log in and obtain the flag.

The term rate-limiting is typically associated with security measures. In this context, it refers to the control of the frequency at which a particular action can be performed.

Let’s put this theory to the test and change v2 to v1, then send our request. Interestingly, we find that we are able to send the request without encountering the rate-limiting issue.

With this newfound knowledge, we could potentially launch an attack. This could be done by setting the value as payload position and adjusting the payload option as a number, incrementing from 1000 to 1700, one step at a time.

Through this methodical approach, we achieved success on the 1655th attempt and successfully obtained the FLAG!!!


10. Insufficient logging and monitoring

Insufficient logging and monitoring refer to the lack of proper mechanisms to detect, log, and monitor unauthorized access and other security events. This weakness allows attackers to remain undetected, enabling them to persist within the system, perform lateral movements, and potentially compromise critical systems.

Explanation

Importance of Logging and Monitoring:

Common Issues:

Scenario Description

In this scenario, we highlight the significance of logging and monitoring in preventing attackers from remaining undetected within a system. Since this is a design flaw, it doesn’t require a specific walkthrough to exploit. Instead, the focus is on how proper logging and monitoring could prevent potential security breaches.

Example:

Suppose an attacker gains access to the system and performs unauthorized activities. Without sufficient logging and monitoring:

Implementation of Logging and Monitoring:

  1. Detailed Logging:

    • Capture detailed logs for all critical activities (e.g., logins, data access, changes to settings).
    • Include user details, timestamps, IP addresses, and action details.
  2. Centralized Log Management:

    • Use centralized log management systems to aggregate and analyze logs from different sources.
  3. Real-Time Monitoring:

    • Implement real-time monitoring tools to detect and alert on suspicious activities immediately.
  4. Retention Policies:

    • Establish log retention policies to ensure logs are kept for an adequate period for forensic analysis.
  5. Regular Audits:

    • Conduct regular audits of logs to identify patterns or anomalies that might indicate security issues.

Conclusion

In this comprehensive guide, we have explored ten critical API vulnerabilities as outlined by OWASP, demonstrating how these vulnerabilities can be exploited using the vAPI framework. Each vulnerability represents a significant risk to API security and highlights common pitfalls that developers and organizations must address to secure their APIs effectively.

Key Takeaways

By addressing these vulnerabilities proactively and adhering to best practices, organizations can significantly enhance the security posture of their APIs, safeguarding sensitive data and maintaining trust with users and stakeholders. Remember, securing APIs is an ongoing process that requires diligence, awareness, and adaptation to evolving threats and best practices in cybersecurity.